import { DeepPartial, FindManyOptions, UpdateResult } from "typeorm";
import { Comment } from "../entities";
import { AppDataSource } from "../data-source";

export class CommentService {
  private static readonly commentRepository =
    AppDataSource.getRepository(Comment);

  public static async create(payload: DeepPartial<Comment>): Promise<Comment> {
    const create = this.commentRepository.create(payload);
    return this.commentRepository.save(create);
  }

  public static async findById(id: Comment["id"]): Promise<Comment | null> {
    return this.commentRepository.findOne({
      where: { id },
      relations: ["user"],
    });
  }

  public static async find(
    options: FindManyOptions<Comment>,
  ): Promise<[Comment[], number]> {
    return this.commentRepository.findAndCount({
      ...options,
      relations: ["user"],
    });
  }

  public static async update(
    id: Comment["id"],
    payload: DeepPartial<Comment>,
  ): Promise<UpdateResult> {
    return this.commentRepository.update({ id }, payload);
  }

  public static async remove(comment: Comment): Promise<Comment> {
    return this.commentRepository.remove(comment);
  }
}
